<template>
  <el-popover
    ref="popover"
    v-bind="$props"
    v-model="innerValue"
    v-on="$listeners"
    :popper-class="innerPopperClass"
  >
    <template slot="reference">
      <slot name="reference"></slot>
    </template>
    <component v-if="contentComponent" :is="contentComponent"></component>
    <slot v-else></slot>
  </el-popover>
</template>
<script>
import ElPopover from 'element-ui/lib/popover'
import 'element-ui/lib/theme-chalk/popover.css'

export default {
  name: 'UiPopover',
  model: {
    prop: 'visible',
    event: 'input'
  },
  props: Object.assign({}, ElPopover.props, {
    visible: {
      type: Boolean,
      default: false
    },
    placement: {
      type: String,
      default: 'bottom'
    }
  }),
  components: {
    ElPopover
  },
  data () {
    return {
      contentComponent: null
    }
  },
  computed: {
    innerValue: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    innerPopperClass() {
      return ['ui-popover__wrap', this.popperClass].join(' ')
    }
  },
  methods: {
    doLayout () {
      this.$refs.popover && this.$refs.popover.updatePopper()
    },
    setReferenceElm ($el) {
      clearTimeout(this._timer)
      this._timer = setTimeout(() => {
        if (this.$refs.popover.popperJS) {
          this.$refs.popover.popperJS._reference = $el
        } else {
          this.$refs.popover.referenceElm = $el
        }
        this.$refs.popover.updatePopper()
      }, 30)
    },
    setContentComponent (component) {
      this.contentComponent = component
    }
  },
  beforeDestroy () {
    clearTimeout(this._timer)
  }
}
</script>
<style>
.el-popover.ui-popover__wrap{
  color: inherit;
}
.ui-popover__wrap.el-popover{
  padding: 0;
  min-width: auto;
}
</style>
